var data_weather, WEEKDAY, fxDate, humidity, tempMax, tempMin, humidity, precip, textDay, textNight, airQuality, uvIndex;
WEEKDAY = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
fxDate = ['2023-10-16', '2023-10-17', '2023-10-18', '2023-10-19', '2023-10-20', '2023-10-21', '2023-10-22'];
humidity = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2];
tempMax = [30, 28, 26, 25, 27, 29, 31];
tempMin = [20, 19, 18, 17, 16, 15, 14];
precip = [0, 0, 0.1, 0.2, 0.3, 0.4, 0.5];
textDay = ['晴', '多云', '阴', '小雨', '中雨', '大雨', '暴雨'];
textNight = ['晴', '多云', '阴', '小雨', '中雨', '大雨', '暴雨'];
uvIndex = [1, 2, 3, 4, 5, 6, 7];
airQuality = 0.5;
iconDay = [100, 104, 105, 106, 107, 108, 109];
iconNight = [200, 204, 205, 206, 207, 208, 209];
textcolor = '#eee';

$.ajax({
    url: 'http://127.0.0.1:5000/weather',
    type: 'POST',
    success: function (res) {
        data_weather = res.data
        console.log(data_weather);
        WEEKDAY = data_weather.WEEKDAY
        fxDate = data_weather.fxDate
        humidity = data_weather.humidity
        tempMax = data_weather.tempMax
        tempMin = data_weather.tempMin
        precip = data_weather.precip
        textDay = data_weather.textDay
        textNight = data_weather.textNight
        uvIndex = data_weather.uvIndex
        iconDay = data_weather.iconDay
        iconNight = data_weather.iconNight
        module();
        calculateAverageTemperature()
    },
    error: function () {
        alert(res.msg)
    }
});
$.ajax({
    url: 'http://127.0.0.1:5000/airQuality',
    type: 'POST',
    success: function (res) {
        airQuality = res.data / 100;
        airQuality123();
    },
    error: function () {
        alert(res.msg)
    }
});
// airQuality123();

$(document).ready(function () {
    // 监听更新数据按钮的点击事件
    $('#update-data').on('click', function () {
        $.ajax({
            url: 'http://127.0.0.1:5000/update',
            type: 'POST',
            success: function (response) {
                console.log('数据更新成功', response);
                // 可在此添加更新页面数据的逻辑
            },
            error: function (error) {
                console.error('数据更新失败', error);
            }
        });
    });

    // 新增监听切换背景按钮的点击事件
    $('#change-background').on('click', function () {
        var currentBackground = $('body').css('background-image');
        if (currentBackground.includes('beijing.png')) {
            $('body').css('background-image', "url('../png/xinyang-Map.png'), url('../png/beijing2.jpg')");
        } else {
            $('body').css('background-image', "url('../png/xinyang-Map.png'), url('../png/beijing.png')");
        }
    });



});

function calculateAverageTemperature() {
    // let totalTemp = tempMax.reduce((acc, curr) => acc + curr, 0) + tempMin.reduce((acc, curr) => acc + curr, 0);
    // let averageTemp = (totalTemp / (tempMax.length + tempMin.length)).toFixed(1); // 保留一位小数
    let totalTempMax = tempMax.reduce((acc, curr) => acc + curr, 0);
    let averageTempMax = (totalTempMax / tempMax.length).toFixed(1);
    let totalTempMin = tempMin.reduce((acc, curr) => acc + curr, 0);
    let averageTempMin = (totalTempMin / tempMax.length).toFixed(1);
    $('#average-max-temp').text(`七日平均最高气温：${averageTempMax}°C`);
    $('#average-min-temp').text(`七日平均最低气温：${averageTempMin}°C`);
}



function airQuality123() {

    var chartDom = document.getElementById('airQuality');
    var myChart = echarts.init(chartDom);
    var option;
    option = {
        title: {
            text: '空气指数',
            left: 'center',
            textStyle: {
                color: textcolor
            }
        },
        series: [
            {
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                center: ['50%', '75%'],
                radius: '100%',
                min: 0,
                max: 1,
                splitNumber: 8,
                axisLine: {
                    lineStyle: {
                        width: 6,
                        color: [
                            [0.25, '#7CFFB2'],
                            [0.5, '#58D9F9'],
                            [0.75, '#FDDD60'],
                            [1, '#FF6E76']
                        ]
                    }
                },
                pointer: {
                    icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
                    length: '12%',
                    width: 20,
                    offsetCenter: [0, '-60%'],
                    itemStyle: {
                        color: 'auto'
                    }
                },
                axisTick: {
                    length: 12,
                    lineStyle: {
                        color: 'auto',
                        width: 2
                    }
                },
                splitLine: {
                    length: 20,
                    lineStyle: {
                        color: 'auto',
                        width: 5
                    }
                },
                axisLabel: {
                    color: '#464646',
                    fontSize: 20,
                    distance: -60,
                    rotate: 'tangential',
                    formatter: function (value) {
                        if (value === 0.875) {
                            return;
                        } else if (value === 0.625) {
                            return;
                        } else if (value === 0.375) {
                            return;
                        } else if (value === 0.125) {
                            return;
                        }
                        return '';
                    }
                },
                title: {
                    offsetCenter: [0, '-10%'],
                    fontSize: 20
                },
                detail: {
                    fontSize: 30,
                    offsetCenter: [0, '-35%'],
                    valueAnimation: true,
                    formatter: function (value) {
                        return Math.round(value * 100) + '';
                    },
                    color: 'inherit'
                },
                data: [
                    {
                        value: airQuality,
                        name: 'airQuality'
                    }
                ]
            }
        ]
    };


    option && myChart.setOption(option);
}

function module() {

    var chartDom = document.getElementById('weather');

    // 清空weather容器，准备插入SVG和文本
    chartDom.innerHTML = '';

    for (let i = 0; i < tempMax.length; i++) {
        // 创建一个容器div
        let dayDiv = document.createElement('div');
        dayDiv.className = 'weather-day';

        // 根据iconDay数值拼接SVG文件路径，假设svg文件命名规则为 icon{iconDay}.svg，且放在svg目录下
        let svgPath = `./icons/${iconDay[i]}.svg`;

        // 创建img标签加载svg
        let img = document.createElement('img');
        img.src = svgPath;
        img.alt = textDay[i];
        img.className = 'weather-icon-svg';

        // 创建p标签显示最高温度
        let pTemp = document.createElement('p');
        pTemp.className = 'temp-max';
        pTemp.textContent = tempMax[i] + '°C';

        // 创建p标签显示白天天气描述
        let pText = document.createElement('p');
        pText.className = 'weather-desc';
        pText.textContent = textDay[i];

        // 组装
        dayDiv.appendChild(img);
        dayDiv.appendChild(pTemp);
        dayDiv.appendChild(pText);

        chartDom.appendChild(dayDiv);
    }


    var chartDom = document.getElementById('temperature');
    var temperature = echarts.init(chartDom);
    var option2;

    option2 = {
        title: {
            text: '七日气温'
            , textStyle: {
                color: textcolor
            }
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['最高气温', '最低气温'],
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: WEEKDAY,
            axisLabel: {
                color: textcolor
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '最高气温',
                type: 'line',
                stack: 'Total',
                data: tempMax
            },
            {
                name: '最低气温',
                type: 'line',
                stack: 'Total',
                data: tempMin
            },

        ]
    };

    temperature.setOption(option2);


    var rainFalldom = document.getElementById('rainFall');
    var rainFall = echarts.init(rainFalldom);
    var option1;

    option1 = {
        title: {
            text: '降雨量',
            subtext: '单位：毫米',
            left: 'center',
            textStyle: {
                color: textcolor
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: WEEKDAY
            , axisLabel: {
                color: textcolor
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: precip,
                type: 'line',
                areaStyle: {}
            }
        ]
    };

    rainFall.setOption(option1);


    var chartDom = document.getElementById('humidity');
    var myChart = echarts.init(chartDom);
    var option;

    option = {
        title: {
            text: '空气湿度',
            left: 'center',
            textStyle: {
                color: textcolor
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                return params[0].name + ': ' + params[0].value + '%'; // 显示百分比
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: WEEKDAY,
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    color: textcolor
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                max: 100,
                show: false
            }
        ],
        series: [
            {
                name: 'Direct',
                type: 'bar',
                barWidth: '60%',
                data: humidity.map(h => h)
            }
        ]
    };

    option && myChart.setOption(option);


    var chartDom = document.getElementById('ultraviolet');
    var myChart = echarts.init(chartDom);
    var option;

    var series = [
        {
            data: uvIndex,
            type: 'bar',
            stack: 'a',
            name: 'a'
        }
    ];

    option = {
        title: {
            text: '紫外线强度',
            left: 'center',
            textStyle: {
                color: textcolor
            }
        },
        xAxis: {
            type: 'category',
            data: WEEKDAY
            , axisLabel: {
                color: textcolor
            }
        },
        yAxis: {
            type: 'value'
        },
        series: series
    };

    option && myChart.setOption(option);
}